import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import NProgress from 'nprogress'
import fetchJsonp from 'fetch-jsonp'

const service = axios.create({
    baseURL: '/api',
    timeout: 3000
})

const startProgress = () => {
    NProgress.start()
}

const stopProgress = () => {
    NProgress && NProgress.isStarted() && NProgress.done()
}

service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        startProgress()
        if (config.headers) {
            // config.headers['X-Requested-With'] = 'XMLHttpRequest'
        }
        return config
    }, () => {

    }

)

service.interceptors.response.use(
    (res: AxiosResponse) => {
        stopProgress()
        return res
    }, () => {
        stopProgress()
    }
)

export const GET = (url: string, params?: object, config?: object) => {
    return service.get(url, { params, ...config })
}

export const Fetch = (url:string,config:object = {}) => {
    return new Promise((resolve,reject) => {
        fetchJsonp(url,config).then(res => {
            res.json().then(data => {
                resolve(data)
            })
        }).catch((err) => {
            console.log(err)
            reject(err)
        })
    })
}

export default service